package com.pets.springboot_petshop.service.impl;

import com.pets.springboot_petshop.entity.Shoppingcart;
import com.pets.springboot_petshop.mapper.ShoppingcartMapper;
import com.pets.springboot_petshop.service.ShoppingcartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @Author: wxk
 * @Email: 2089967794@qq.com
 * @Date: 2024/10/15 上午11:09 周二
 * @Description: 购物车服务层
 */
@Service
public class ShoppingcartServiceImpl implements ShoppingcartService {
    @Autowired
    private ShoppingcartMapper shoppingcartMapper;

    @Override
    public Shoppingcart select(int id) {
        return shoppingcartMapper.select(id);
    }

    @Override
    public List<Shoppingcart> selectuser_id(int user_id) {
        return shoppingcartMapper.selectuser_id(user_id);
    }

    @Override
    public List<Shoppingcart> selectproduct_id(int product_id) {
        return shoppingcartMapper.selectproduct_id(product_id);
    }

    @Override
    public List<Shoppingcart> findAll() {
        return shoppingcartMapper.findAll();
    }

    @Override
    public List<Shoppingcart> selectcheck(Shoppingcart shoppingcart) {
        return shoppingcartMapper.selectcheck(shoppingcart);
    }

    @Override
    public int add(Shoppingcart shoppingcart) {
        int a = shoppingcartMapper.add(shoppingcart);
        System.out.println("Generated Order ID: " + a);
        return a;
    }

    @Override
    public int delete(int user_id) {
        return shoppingcartMapper.delete(user_id);
    }


    @Override
    public int update(Shoppingcart shoppingcart) {
        return shoppingcartMapper.update(shoppingcart);
    }

    @Override
    public int updatequantity(Shoppingcart shoppingcart) {
        return shoppingcartMapper.updatequantity(shoppingcart);
    }

    @Override
    public int updatecheck(Shoppingcart shoppingcart) {
        return shoppingcartMapper.updatecheck(shoppingcart);
    }

    @Override
    public boolean updateCheckForAll(int user_id) {
        // 使用提供的Mapper方法查询当前用户的购物车项
        List<Shoppingcart> shoppingcarts = shoppingcartMapper.selectuser_id(user_id);

        // 检查购物车是否为空
        if (shoppingcarts == null || shoppingcarts.isEmpty()) {
            return false;
        }

        // 决定新的check状态
        boolean allChecked = true;
        for (Shoppingcart cartItem : shoppingcarts) {
            if (!"1".equals(cartItem.getCheck())) {
                allChecked = false;
                break;
            }
        }
        String newCheck = allChecked ? "0" : "1";

        // 调用MyBatis映射器的批量更新方法
        return shoppingcartMapper.updateCheckForAll(user_id, newCheck) > 0;
    }


    @Override
    public Shoppingcart selectupdate(Shoppingcart shoppingcart) {
        return shoppingcartMapper.selectupdate(shoppingcart);
    }

}
